// CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build
package main

import (
	"ecld.com/prowatcher/pb"
	"github.com/go-ini/ini"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	"log"
	"net"
	"os"
	"os/signal"
	"strconv"
	"syscall"
)

var (
	file              *os.File
	logger            *log.Logger
	s                 *grpc.Server
	as                *authServer
	port              = getOption(SECTION, PORT)
	dsn               = getOption(SECTION, DSN)
	logFile           = getOption(SECTION, LOGFILE)
	tokenRenewTime, _ = strconv.ParseInt(getOption(SECTION, TOKEN_RENEW_TIME), 10, 64)
	maxOpenConns, _   = strconv.Atoi(getOption(SECTION, MAX_OPEN_CONN))
	maxIdleConns, _   = strconv.Atoi(getOption(SECTION, MAX_IDLE_CONN))
)

func main() {

	var err error

	if _, err = os.Stat(logFile); os.IsNotExist(err) {
		file, err = os.Create(logFile)
	} else {
		file, err = os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND, 0666)
	}
	if err != nil {
		log.Fatal("fail to create logger file!")
	}

	logger = log.New(file, INFO, log.LstdFlags)

	logger.Printf("MAS AUTH SERVER %s BOOT", VERSION)

	addShutDownHook()

	lis, err := net.Listen("tcp", port)
	if err != nil {
		logger.SetPrefix(ERROR)
		logger.Fatalf("failed to listen: %v", err.Error())
	}

	s = grpc.NewServer()
	as = NewAuthServer()
	pb.RegisterAuthServiceServer(s, as)
	reflection.Register(s)

	logger.Println("gRPC Server start, listening on", port)

	if err := s.Serve(lis); err != nil {
		logger.SetPrefix(ERROR)
		logger.Fatalf("failed to serve: %v", err)
	}

}

func getOption(section string, key string) (conf string) {
	cfg, err := ini.Load(CONFIG)
	conf = cfg.Section(section).Key(key).String()
	if err != nil {
		log.Fatal(err)
	}
	return conf
}

func addShutDownHook() {
	signals := make(chan os.Signal)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	go func() {
		switch <-signals {
		case syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
			logger.SetPrefix(INFO)
			logger.Println("shutdown hook")
			as.handler.Store().stop()
			s.Stop()
			logger.Println("shutdown")
			file.Close()
			os.Exit(0)

		}
	}()
}
